<?php 
class Jolly_Masa_Model_Payment extends Mage_Payment_Model_Method_Abstract{
	protected $_code  = 'masa_payment';
    protected $_formBlockType = 'masa/form';
	//protected $_infoBlockType = 'masa/form';
	
	
	
	public function getMasaUrl(){
		$url = $this->getConfigData('gateway');
		if(empty($url)){
			return false;
		}
		return $url;
	}
	
	public function getOrderPlaceRedirectUrl()
	{
      return Mage::getUrl('masa/payment/redirect');
	}
	
	public function assignData($data){
		if (!($data instanceof Varien_Object)) {
			$data = new Varien_Object($data);
		}
		$info = $this->getInfoInstance();
		
		$info->setPayType($data->getPayType());	
		Mage::getSingleton('core/session')->setPayType($data->getPayType());
		return $this;
	}
	
	public function validate()
	{
		parent::validate();
	 
		$info = $this->getInfoInstance();
	 
		$pay_type   = $info->getPayType();
		$errorMsg = '';
		if (empty($pay_type)) {
			$errorCode = 'invalid_data';
			$errorMsg  = $this->_getHelper()
							  ->__('Check No and Date are required fields');
		}
	  
		if ($errorMsg) {
			Mage::throwException($errorMsg);
		}
		return $this;
	}
	
	/**
     *  Return back URL
     *
     *  @return	  string URL
     */
	protected function getReturnURL()
	{
		return Mage::getUrl('masa/payment/success', array('_secure' => true));
	}

	/**
	 *  Return URL for Alipay success response
	 *
	 *  @return	  string URL
	 */
	protected function getSuccessURL()
	{
		return Mage::getUrl('masa/payment/success', array('_secure' => true));
	}

    /**
     *  Return URL for Alipay failure response
     *
     *  @return	  string URL
     */
    protected function getErrorURL()
    {
        return Mage::getUrl('masa/payment/error', array('_secure' => true));
    }
	
	/**
	 *  Return URL for Alipay notify response
	 *
	 *  @return	  string URL
	 */
	protected function getNotifyURL()
	{
		return Mage::getUrl('masa/payment/notify/', array('_secure' => true));
	}
	
	public function getStandardCheckoutFormFields()
    {
		$session = Mage::getSingleton('checkout/session');
        
        $order = $this->getOrder();
        if (!($order instanceof Mage_Sales_Model_Order)) {
            Mage::throwException($this->_getHelper()->__('Cannot retrieve order object'));
        }
		
		$pay_type = Mage::getSingleton('core/session')->getPayType();
		
		
		$items = $order->getAllItems();
		$good_names = '';
		$good_desc = '';
		foreach($items as $item){
			
			$good_names .= $item->getName() . "|";
			$good_desc .= $item->getName() . "^" . $item->getSku() . "^" . $item->getQtyToInvoice() . "^" . $item->getPrice() . "^" . $item->getProduct()->getProductUrl();
		}
		
		
		$order_id = $order->getRealOrderId();
		$order_amount = $order->getGrandTotal()  * 100;//注意，这里是美分为单位，所以要把美金转换成美分，*100
		$receiveName = $order->getBillingAddress()->getName();
		$receiveAddress = $order->getBillingAddress()->getStreetFull();
		$receivePostCode = $order->getBillingAddress()->getPostcode();
		$receiveTel = $order->getBillingAddress()->getTelephone();
		$subtime = date("YmdHis");
		$pageUrl = $this->getReturnURL();
		$bgUrl = $this->getNotifyURL();
		
		$merchantId = $this->getConfigData('merchant');
		$key = $this->getConfigData('key');
		
		$signStr = "version=1.0&merchantId=$merchantId&charset=utf-8&language=en&signType=SHA256&merchantOrderNo=$order_id&goodsName=$good_names&goodsDesc=$good_desc&currencyCode=USD&orderAmount=$order_amount&payMode=10&orgCode=$pay_type&directFlag=D&allowDuplicate=N&submitTime=$subtime&expiryTime=&pageUrl=$pageUrl&bgUrl=$bgUrl&key=$key";
		
		
		
		$signMsg = strtoupper(hash("sha256", $signStr));
		
		$parameter = array(
			'version' =>'1.0', //版本
			'charset'=>'utf-8', //编码
			'language'=>'en',  //语言
			'signType'=>'SHA256',  //加密方式
			'merchantOrderNo'=> $order_id,  //订单号
			'merchantId'=>$merchantId, //商户号，由Masa分配
			'goodsName'=>$good_names, //商品名称
			'goodsDesc'=>$good_desc, //商品描述
			'currencyCode'=>'USD', //币种
			'orderAmount'=>$order_amount, //订单金额
			'payMode'=>10,//支付方式
			'orgCode'=>$pay_type,//付款机构代码
			'directFlag'=>'D',//是否直连
			'allowDuplicate'=>'N',//是否可重复支付
			'submitTime'=>$subtime,//提交时间
			'expiryTime'=>'',//失效时间
			'pageUrl'=>$pageUrl,//前台回调地址，用于支付成功之后跳转的地址
			'bgUrl'=>$bgUrl,//通知 URL,通知商户订单支付结果的地址
			'receiveName'=>$receiveName,//收货人姓名 风控属性
			'receiveAddress'=>$receiveAddress,//收货地址
			'receivePostCode'=>$receivePostCode,//收货邮编
			'receiveTel'=>$receiveTel,//收货电话
			'orderIp'=>$this->get_client_ip(),//下单 IP
			'signMsg'=>$signMsg,//签名
		);
		
		return $parameter;
		
	}
	
	function get_client_ip() {
		$ipaddress = '';
		 if (getenv('HTTP_CLIENT_IP'))
			 $ipaddress = getenv('HTTP_CLIENT_IP');
		 else if(getenv('HTTP_X_FORWARDED_FOR'))
			 $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
		 else if(getenv('HTTP_X_FORWARDED'))
			 $ipaddress = getenv('HTTP_X_FORWARDED');
		 else if(getenv('HTTP_FORWARDED_FOR'))
			 $ipaddress = getenv('HTTP_FORWARDED_FOR');
		 else if(getenv('HTTP_FORWARDED'))
			$ipaddress = getenv('HTTP_FORWARDED');
		 else if(getenv('REMOTE_ADDR'))
			 $ipaddress = getenv('REMOTE_ADDR');
		 else
			 $ipaddress = '127.0.0.1';

		 return $ipaddress; 
	}
	
	
}